package com.Dao.Imp;
import com.Dao.UploadBookDao;
import com.Utils.C3P0Utils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Service;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
@Service
@Slf4j
public class UploadBookDaoImp implements UploadBookDao {
    @Override
    public void insertExamineBook(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {
        request.setCharacterEncoding("UTF-8");//防止用户输入中文导致乱码
        response.setContentType("text/html;charset=UTF-8");
        QueryRunner queryRunner=new QueryRunner(C3P0Utils.getDataSource());
        String sql="insert into bookTemportary(author,bookName,bookImage,background,profile,snopsis,mainsignature," +
                "signature2,signature3,signature4,signature5,file)values(?,?,?,?,?,?,?,?,?,?,?,?)";
        Part part= request.getPart("myFile");
        InputStream fileContent = part.getInputStream();

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[4096];
        int bytesRead;
        while ((bytesRead = fileContent.read(buffer)) != -1) {
            byteArrayOutputStream.write(buffer, 0, bytesRead);
        }

        byte[] fileBytes = byteArrayOutputStream.toByteArray();

        String author=request.getParameter("author");
        System.out.println(author);
        String bookName=request.getParameter("bookName");
        String bookImage=request.getParameter("bookImage");
        String background=request.getParameter("background");
        String profile=request.getParameter("profile");
        String snopsis=request.getParameter("snopsis");
        String mainsignature=request.getParameter("mainsignature");
        String signature2=request.getParameter("signature2");
        String signature3=request.getParameter("signature3");
        String signature4=request.getParameter("signature4");
        String signature5=request.getParameter("signature5");
        queryRunner.update(sql,author,bookName,bookImage,background,profile,snopsis,mainsignature,signature2,
                signature3,signature4,signature5,fileBytes);
    }
}
